package com.lovepick.fragment;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lovepick.R;
import com.lovepick.adapter.OrderInfoAdapter;
import com.lovepick.bean.OrderInfo;
import com.lovepick.http.HttpThread;
import com.lovepick.util.BaseUtils;
import com.lovepick.util.Constant;
import com.lovepick.util.OrderState;

/**
 * @author Liutong
 * <h1>司机用户查看申请乘客列表</h1>
 *
 * <p>该类只有当用户身份是司机, 并且查看某条有新申请的订单时才会出现.</p>
 *
 */
public class OrderInfoFragment extends Fragment
{
	public static final String ARG_INFOS = "infos";
	public static final String ARG_SRC = "src";
	public static final String ARG_DEST = "dest";
	public static final String ARG_ORDER_ID = "order_id";
	public static final String ARG_USER_ID = "user_id";
	public static final String ARG_FREE_COUNT = "free_count";

	private static final String TAG = "OrderInfoFragment";
	private OrderInfoAdapter mAdapter =null;;
	private List<OrderInfo> mOrderInfos = null;

	private ListView mInfoListView;
	private ProgressBar mBar;
	private TextView mSrcText;
	private TextView mDestText;
	private TextView mCountText;

	private int mOrderID;

	private OrderInfoHandler mHandler = null;
	private HttpThread mThread = null;
	private boolean mIsAccept = true;

	public static OrderInfoFragment createInstance(Bundle args)
	{
		OrderInfoFragment fragment = new OrderInfoFragment();
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		setHasOptionsMenu(true);
		findViews();
		mBar.setVisibility(View.GONE);
		Bundle args = getArguments();
		refreshInfos(args);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.order_info, container, false);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
	{
		inflater.inflate(R.menu.order_info, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.menu_refresh_order_info:
				refreshApplyList();
				return true;

			default:
				return super.onOptionsItemSelected(item);

		}
	}

	public void refreshInfos(Bundle args)
	{
		mIsAccept = true;
		final String json = args.getString(ARG_INFOS);
		String src = args.getString(ARG_SRC);
		String dest = args.getString(ARG_DEST);
		mOrderID = args.getInt(ARG_ORDER_ID);

		int freeCount = args.getInt(ARG_FREE_COUNT);
		mSrcText.setText(src);
		mDestText.setText(dest);
		mCountText.setText(String.valueOf(freeCount));

		mHandler = new OrderInfoHandler(this);
		mOrderInfos = BaseUtils.getOrderInfos(json);
		if (null == mOrderInfos)
		{
			mOrderInfos = new ArrayList<OrderInfo>();
		}
		mAdapter = new OrderInfoAdapter(getActivity(), mOrderInfos, false);
		mInfoListView.setAdapter(mAdapter);
		mInfoListView.setOnItemClickListener(mListener);
	}

	private void refreshApplyList()
	{
		mIsAccept = false;
		String url = Constant.HTTP_URL_ORDER_APPLY_INFOS + "/" + mOrderID;
		mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_GET, url, null);
		mThread.start();
		mBar.setVisibility(View.VISIBLE);
		BaseUtils.showToast(getActivity(), R.string.refresh_order_info);
	}

	private void findViews()
	{
		mSrcText = (TextView) getActivity().findViewById(R.id.order_info_src);
		mDestText = (TextView) getActivity().findViewById(R.id.order_info_dest);
		mCountText = (TextView) getActivity().findViewById(R.id.order_info_count);
		mInfoListView = (ListView) getActivity().findViewById(R.id.lv_order_info);
		mBar = (ProgressBar) getActivity().findViewById(R.id.progBar_apply);
	}

	private AdapterView.OnItemClickListener mListener = new AdapterView.OnItemClickListener()
	{

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id)
		{
			// TODO Auto-generated method stub
			final OrderInfo orderInfo = mOrderInfos.get(position);
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

			if (OrderState.FINISHED.equals(orderInfo.getState()))
			{
				builder.setTitle(R.string.prompt);
				builder.setMessage(R.string.order_finished);
				builder.setNegativeButton(R.string.ok, null);
			}
			else
			{
				builder.setTitle(R.string.dialog_title_apply_accept);
				String msg = getString(R.string.order_info_passenger) + orderInfo.getPassengerName();
				msg += "\n";
				msg += getString(R.string.order_info_route_id) + orderInfo.getRouteID();
				msg += "\n";
				msg += getString(R.string.order_info_money) + orderInfo.getMoney();
				msg += "\n";
				msg += getString(R.string.order_info_count) + orderInfo.getCount();
				builder.setMessage(msg);
				builder.setPositiveButton(R.string.accept, new DialogInterface.OnClickListener()
				{

					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						// TODO Auto-generated method stub
						String url = Constant.HTTP_URL_ORDER_ACCEPT + "/" +
								orderInfo.getOrderID() + "/" +
								orderInfo.getRouteID();
						mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_GET, url, null);
						mThread.start();
						mBar.setVisibility(View.VISIBLE);
					}
				});
				builder.setNegativeButton(R.string.cancel, null);
			}

			builder.create().show();
		}
	};

	private static class OrderInfoHandler extends Handler
	{
		private WeakReference<OrderInfoFragment> mReference;
		private OrderInfoFragment mFragment;

		public OrderInfoHandler(OrderInfoFragment fragment)
		{
			mReference = new WeakReference<OrderInfoFragment>(fragment);
		}

		@Override
		public void handleMessage(Message msg)
		{
			mFragment = mReference.get();
			switch (msg.what)
			{
				case Constant.MSG_HTTP_SUCCESS:
					mFragment.mBar.setVisibility(View.GONE);
					String result = msg.getData().getString(Constant.HTTP_RESULT);

					Log.i(TAG, result);
					if (mFragment.mIsAccept)
					{
						Log.i(TAG, "###接受拼车申请的返回结果###");
						if (Constant.HTTP_ORDER_ACCEPT_COUNT_NOT_ENOUGH.equals(result))
						{
							BaseUtils.showToast(mFragment.getActivity(), R.string.count_not_enough);
						}
						else if (Constant.HTTP_ORDER_ACCEPT_NO_PASSENGER.equals(result))
						{
							BaseUtils.showToast(mFragment.getActivity(), R.string.no_passenger);
						}
						else
						{
							mFragment.mOrderInfos = BaseUtils.getOrderInfos(result);
							if (null == mFragment.mOrderInfos)
							{
								BaseUtils.showToast(mFragment.getActivity(), R.string.accept_fail);
							}
							else
							{
								BaseUtils.showToast(mFragment.getActivity(), R.string.accept_success);
								int freeCount = mFragment.mOrderInfos.get( mFragment.mOrderInfos.size() - 1).getFreeCount();
								mFragment.mCountText.setText(String.valueOf(freeCount));
								mFragment.mAdapter = new OrderInfoAdapter(
										mFragment.getActivity(), mFragment.mOrderInfos, false);
								mFragment.mInfoListView.setAdapter(mFragment.mAdapter);
								mFragment.mInfoListView.setOnItemClickListener(mFragment.mListener);
							}
						}
						mFragment.mIsAccept = false;
					}
					else
					{
						if (result.startsWith(Constant.JSON_ARRAY_START))
						{
							mFragment.mOrderInfos = BaseUtils.getOrderInfos(result);
							if (null == mFragment.mOrderInfos)
							{
								mFragment.mOrderInfos = new ArrayList<OrderInfo>();
							}
							BaseUtils.showToast(mFragment.getActivity(), R.string.refresh_order_info_success);
							mFragment.mAdapter = new OrderInfoAdapter(
									mFragment.getActivity(), mFragment.mOrderInfos, false);
							mFragment.mInfoListView.setAdapter(mFragment.mAdapter);
							mFragment.mInfoListView.setOnItemClickListener(mFragment.mListener);
						}
						else
						{
							BaseUtils.showToast(mFragment.getActivity(), R.string.refresh_order_info_fail);
						}
						mFragment.mIsAccept = true;
					}

					break;

				case Constant.MSG_HTTP_ERROR:
					mFragment.mBar.setVisibility(View.GONE);
					BaseUtils.showToast(mFragment.getActivity(), R.string.network_error);
					break;

				default:
					mFragment.mBar.setVisibility(View.GONE);
					break;
			}
		}
	}

}
